<template>
  <div class="app-container">
    <el-card class="box-card">
      <el-form :inline="true" size="mini">
        <el-form-item>
          <el-input
            style="min-width: 195px"
            v-model="listQuery.name"
            placeholder="编号/针对机关/罪名/当事人"
            clearable
            @keyup.enter.native="handleFilter"
          >
          </el-input>
        </el-form-item>
        <el-form-item label="">
          <el-date-picker
            v-model="listQuery.search_date"
            style="min-width: 360px"
            type="daterange"
            align="right"
            unlink-panels
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :picker-options="pickerOptions"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="">
          <el-button
            type="primary"
            size="mini"
            icon="el-icon-search"
            @click.native="handleFilter"
            >查询</el-button
          >
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            >新增{{ this.title }}</el-button
          >
        </el-form-item>
      </el-form>

      <el-table
        :data="introduces"
        border
        v-loading="listLoading"
        fit
        size="small"
        highlight-current-row
        style="width: 100%"
      >
        <el-table-column
          type="index"
          label="#"
          align="center"
        ></el-table-column>
        <el-table-column
          v-for="column in tableColumns"
          :key="column.key"
          :label="column.title"
          :prop="column.key"
          align="center"
          :width="column.width ? column.width : ''"
          :formatter="dataFormatter"
        ></el-table-column>
        <el-table-column align="left" label="操作" width="260px">
          <template slot-scope="scope">
            <el-button
              type="primary"
              size="mini"
              icon="el-icon-edit"
              @click="handleEdit(scope)"
              v-if="scope.row.stamp_confirm != 1"
              >编辑</el-button
            >
            <el-button
              type="success"
              size="mini"
              icon="el-icon-search"
              @click="handleEdit(scope)"
              v-else
              >查看</el-button
            >
            <el-button
              type="warning"
              size="mini"
              icon="el-icon-printer"
              @click="handlePrint(scope.row)"
              v-if="scope.row.apply_confirm == 1"
              >打印</el-button
            >
            <el-button
              type="danger"
              size="mini"
              icon="el-icon-delete"
              @click="handleDelete(scope)"
              v-if="scope.row.apply_confirm != 1 || is_super == true"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="listQuery.page"
        :limit.sync="listQuery.page_size"
        @pagination="getCrimiIntroduceList"
      />
    </el-card>
    <!-- 对话框表单 -->
    <el-dialog :visible.sync="dialogVisible" :title="getTitle" width="800px">
      <el-form
        :model="form"
        :rules="formRules"
        ref="formRef"
        label-width="100px"
        label-position="right"
        style="width: 95%; padding: 0 30px"
        status-icon
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="介绍信编号" prop="code">
              <el-input
                type="text"
                v-model="form.code"
                placeholder="介绍信编号"
                disabled
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="看守所" prop="court">
              <el-input v-model="form.court" placeholder="看守所" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="律师" prop="lawyer">
              <el-input
                v-model="form.lawyer"
                placeholder="律师"
                clearable
                @change="handleChange"
                @clear="handleClear"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="执业证号" prop="cert_no">
              <el-input
                v-model="form.cert_no"
                placeholder="执业证号"
                clearable
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="身份证号" prop="id_card">
              <el-input
                v-model="form.id_card"
                placeholder="身份证号"
                clearable
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="联系电话" prop="telephone">
              <el-input
                v-model="form.telephone"
                placeholder="联系电话"
                clearable
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="罪名" prop="reason">
              <el-input v-model="form.reason" placeholder="罪名" clearable />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="当事人" prop="party">
              <el-input v-model="form.party" placeholder="当事人" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="申请确认" prop="apply_confirm">
              <el-radio-group
                v-model="form.apply_confirm"
                :disabled="form.apply_time != null"
              >
                <el-radio :label="true">确定</el-radio>
                <el-radio :label="false">暂不</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer">
        <el-button type="danger" @click="dialogVisible = false">取消</el-button>
        <el-button
          type="primary"
          v-if="form.stamp_confirm != 1"
          @click="handleSave(false)"
          >保存</el-button
        >
        <el-button
          type="primary"
          @click="handleSave(true)"
          v-if="form.stamp_confirm != 1"
          >保存并打印</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import {
  getCrimiIntroduces,
  addCrimiIntroduce,
  updateCrimiIntroduce,
  delCrimiIntroduce,
} from "@/api/case";
import { getUserList } from "@/api/user";
import { formatDateTime } from "@/utils/datetime";
import Pagination from "@/components/Pagination";

const defaultForm = {
  id: null,
  code: "",
  court: "",
  party: "",
  lawyer: null,
  cert_no: "",
  id_card: "",
  telephone: "",
  reason: "",
  apply_confirm: null,
  user: null,
};

export default {
  name: "CrimiIntroduce",
  data() {
    return {
      form: Object.assign({}, defaultForm),
      formRules: {
        party: [
          {
            type: "string",
            required: true,
            message: "请输入当事人",
            trigger: "blur",
          },
        ],
        reason: [
          {
            type: "string",
            required: true,
            message: "请输入罪名",
            trigger: "blur",
          },
        ],
        court: [
          {
            type: "string",
            required: true,
            message: "请输入看守所",
            trigger: "blur",
          },
        ],
        lawyer: [
          {
            type: "string",
            required: true,
            message: "请输入律师",
            trigger: "blur",
          },
        ],
        apply_confirm: [
          {
            type: "boolean",
            required: true,
            message: "请选择申请确认",
            trigger: "blur",
          },
        ],
      },
      tableColumns: [
        {
          key: "code",
          title: "介绍信编号",
        },

        {
          key: "lawyer",
          title: "律师",
        },
        {
          key: "court",
          title: "看守所",
        },
        {
          key: "party",
          title: "当事人",
        },

        {
          key: "apply_time",
          title: "申请时间",
        },
        {
          key: "stamp_time",
          title: "盖章时间",
        },
      ],
      title: "介绍信",
      dialogVisible: false,
      dialogType: "new",
      introduces: [],
      users: [],

      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        page_size: 15,
        name: null,
        search_date: "",
      },
      pickerOptions: {
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
    };
  },
  computed: {
    ...mapGetters(["uid", "is_super"]),
    getTitle() {
      return this.dialogType == "new"
        ? `新增${this.title}`
        : `编辑${this.title}`;
    },
  },
  components: {
    Pagination,
  },
  created() {
    this.getCrimiIntroduceList();
    this.getAllUser();
  },
  methods: {
    getAllUser() {
      getUserList()
        .then((res) => {
          this.users = res;
        })
        .catch((error) => {
          this.$message.error("读取用户信息失败!");
        });
    },

    handleClear() {
      this.form.cert_no = "";
      this.form.id_card = "";
      this.form.telephone = "";
    },

    handleChange(value) {
      console.log(value);
      let users = this.users;
      let arr_values = value.split("、");
      let lawyers = [];
      this.form.cert_no = "";
      this.form.id_card = "";
      this.form.telephone = "";
      arr_values.forEach((item) => {
        users.forEach((user) => {
          if (user.real_name === item) {
            lawyers.push(user);
          }
        });
      });

      lawyers.forEach((item) => {
        this.form.cert_no += " " + item.cert_no;
        this.form.id_card += " " + item.id_card;
        this.form.telephone += " " + item.telephone;
      });
    },

    getCrimiIntroduceList() {
      this.listLoading = true;
      getCrimiIntroduces(this.listQuery)
        .then((res) => {
          this.introduces = res.results;
          this.listLoading = false;
          this.total = res.count;
        })
        .catch((error) => {
          console.log(error);
          this.$message.error("获取刑事介绍信信息失败!");
          this.listLoading = false;
        });
    },

    dataFormatter(row, column, cellValue, index) {
      if (column.property == "apply_time") {
        return formatDateTime(cellValue);
      } else if (column.property == "stamp_time") {
        return formatDateTime(cellValue);
      } else {
        return cellValue;
      }
    },
    // 查询
    handleFilter() {
      this.listQuery.page = 1;
      this.getCrimiIntroduceList();
    },

    // 增加
    handleAdd() {
      this.form = Object.assign({}, defaultForm);

      this.dialogType = "new";
      this.dialogVisible = true;

      this.$nextTick(() => {
        this.$refs.formRef.clearValidate();
      });
    },
    // 修改用户
    handleEdit(scope) {
      this.form = Object.assign({}, scope.row);
      this.dialogType = "edit";

      this.dialogVisible = true;
      this.$nextTick(() => {
        this.$refs.formRef.clearValidate();
      });
    },
    // 删除用户
    handleDelete({ $index, row }) {
      this.$confirm("确定要删除该案件吗?", "删除提示：", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const res = await delCrimiIntroduce(row.id);
          this.introduces.splice($index, 1);
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch((err) => {
          console.error(err);
        });
    },
    // 保存操作
    async handleSave(flag) {
      this.$refs.formRef.validate(async (valid) => {
        if (!valid) return;

        const isEdit = this.dialogType === "edit";
        let res = null;
        if (isEdit) {
          if (!this.form.user) {
            this.form.user = this.uid;
          }
          res = await updateCrimiIntroduce(this.form);
          const index = this.introduces.findIndex((v) => v.id === res.id);
          this.introduces.splice(index, 1, res);
        } else {
          this.form.user = this.uid;
          res = await addCrimiIntroduce(this.form);
          const { id } = res;
          if (id > 0) {
            this.introduces.unshift(res);
          }
        }

        const { code, party, lawyer } = this.form;
        if (flag) {
          this.$router.push(`/case/crimi_intro_print/${res.id}`);
          return;
        } else {
          this.dialogVisible = false;
        }

        this.$notify({
          title: "Success",
          dangerouslyUseHTMLString: true,
          message: `
              <div>编号: ${code}</div>
              <div>当事人: ${party}</div>
              <div>律师: ${lawyer}</div>
            `,
          type: "success",
        });
      });
    },
    handlePrint(data) {
      this.$router.push(`/case/crimi_intro_print/${data.id}`);
    },
  },
};
</script>

<style lang='scss' scoped>
</style>